<template>
  <div class="view">
    <Panel :title="title">
      <el-form label-position="top">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item :label="$t('m.ClassroomName')" required>
              <el-input v-model="classroom.name" :placeholder="$t('m.ClassroomName')"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('m.ClassroomOpenDate')" required>
              <el-date-picker
                v-model="availableDuration"
                type="daterange"
                align="right"
                start-placeholder="开课时间"
                end-placeholder="结课时间"
                default-value="2021-07-16"
                @change="handleDurationChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('m.ClassroomStudents')">
              <el-table
                v-loading="loadingTable"
                element-loading-text="loading"
                ref="table"
                :data="students"
                style="width: 100%"
                height="350"
                @selection-change="handleSelectionChange">
                <el-table-column
                  type="selection"
                  width="55"
                  :selectable="isSelectable"></el-table-column>
                <el-table-column prop="username" label="学号"></el-table-column>
                <el-table-column prop="real_name" label="姓名"></el-table-column>
                <el-table-column prop="grade" label="年级"
                 :filters="gradeFilters"
                 :filter-method="filterStudents"></el-table-column>
                <el-table-column prop="major" label="专业"
                 :filters="majorFilters"
                 :filter-method="filterStudents"></el-table-column>
                <el-table-column prop="classes" label="班级"
                 :filters="classFilters"
                 :filter-method="filterStudents"></el-table-column>
                <el-table-column
                  align="left">
                  <template slot="header" slot-scope="scope">
                    <el-button
                      size="mini"
                      @click="registerSelectedStudents()">选课</el-button>
                    <el-button
                      size="mini"
                      @click="unregisterSelectedStudents()">取消</el-button>
                  </template>
                  <template slot-scope="scope">
                    <el-button
                      @click="unregisterStudent(scope.$index, scope.row)"
                      size="mini"
                      v-if="classroomHas(scope.row)"
                      type="success">取消</el-button>
                    <el-button v-else
                      size="mini"
                      @click="registerStudent(scope.$index, scope.row)">选课</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                class="page"
                layout="prev, pager, next"
                @current-change="currentChange"
                :page-size="pageSize"
                :total="total">
              </el-pagination>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <save @click.native="saveClassroom"></save>
    </Panel>
  </div>
</template>

<script>
import api from '../../api.js'
export default {
  name: 'CreateClassroom',
  data () {
    return {
      title: '开课',
      availableDuration: null,
      classroom: {
        name: '',
        start: null,
        end: null,
        students: []
      },
      majorFilters: [{
        'text': '软件技术',
        'value': '软件技术'
      }, {
        'text': '计算机应用技术',
        'value': '计算机应用技术'
      }, {
        'text': '大数据技术',
        'value': '大数据技术'
      }, {
        'text': '移动应用开发',
        'value': '移动应用开发'
      }, {
        'text': '云计算技术与应用',
        'value': '云计算技术与应用'
      }],
      classFilters: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
        11, 12, 13, 14, 15, 16, 17, 18, 19, 20].map(item => {
          return {
            'text': item,
            'value': item
          }
        }),
      loadingTable: false,
      total: 0,
      pageSize: 15,
      currentPage: 1,
      students: [],
      selectedStudents: [],
      courseId: null
    }
  },
  mounted () {
    this.courseId = this.$route.params.courseId
    if (this.$route.name === 'edit-classroom') {
      this.title = '编辑开课'
      api.getClassroom(this.$route.params.classroomId).then(res => {
        this.classroom = res.data.data
        this.availableDuration = [this.classroom.start, this.classroom.end]
        this.assembleStudentList(this.classroom.students)
        this.getStudents(1)
      }).catch(() => {
      })
    } else if (this.$route.name === 'create-classroom') {
      this.getStudents(1)
    }
  },
  computed: {
    gradeFilters () {
      let date = new Date()
      let year = date.getFullYear()
      return [{
        'text': year.toString(),
        'value': year.toString()
      }, {
        'text': (year - 1).toString(),
        'value': (year - 1).toString()
      }, {
        'text': (year - 2).toString(),
        'value': (year - 2).toString()
      }]
    }
  },
  methods: {
    getStudents (page) {
      this.loadingTable = true
      api.getStudentList((page - 1) * this.pageSize, this.pageSize, '', 'Regular User').then(res => {
        this.loadingTable = false
        this.total = res.data.data.total
        this.students = res.data.data.results
        this.assembleStudentList(this.students)
      }, res => {
        this.loadingTable = false
      })
    },
    assembleStudentList (students) {
      students.forEach((val, idx) => {
        val.username = val.user.username
      })
    },
    handleDurationChange () {
      this.classroom.start = this.availableDuration[0]
      this.classroom.end = this.availableDuration[1]
    },
    filterStudents (value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    handleSelectionChange (selection) {
      this.selectedStudents = selection
    },
    isSelectable (row, rowIndex) {
      return !this.classroomHas(row)
    },
    currentChange (page) {
      this.currentPage = page
      this.getStudents(page)
    },
    classroomHas (student) {
      for (let item of this.classroom.students) {
        if (item.id === student.id) {
          return true
        }
      }
      return false
    },
    registerStudent (idx, row) {
      // 将此行数据加入classroom的students中
      this.classroom.students.push(row)
    },
    unregisterStudent (idx, row) {
      // 从classroom的students中删除此行数据
      for (let index in this.classroom.students) {
        let student = this.classroom.students[index]
        if (student.id === row.id) {
          this.classroom.students.splice(index, 1)
        }
      }
    },
    registerSelectedStudents () {
      // 将selectedStudents中的数据加入classroom的students中
      this.classroom.students = this.classroom.students.concat(this.selectedStudents)
    },
    unregisterSelectedStudents () {
      this.classroom.students = []
    },
    saveClassroom () {
      let funcName = this.$route.name === 'edit-classroom' ? 'editClassroom' : 'createClassroom'
      let courseId = this.courseId
      this.classroom['course_id'] = courseId
      api[funcName](this.classroom).then(res => {
        this.$router.push({name: 'classroom-list',
          params: {courseId},
          query: {refresh: 'true'}})
      }).catch((e) => {
      })
    }
  }
}
</script>
